﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;
namespace Odyssey.Application
{
    using Implementations;
    public class HostBuilder
    {
        private readonly IConfiguration _configuration;

        private Action<IServiceCollection> _configureServices;
        private ServiceProvider _services;

        public HostBuilder()
        {
            _configuration = new ConfigurationBuilder().AddEnvironmentVariables(prefix: "ASPNETCORE_").Build();
        }

        public IApplicationHost Build()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddSingleton(_configuration);
            serviceCollection.AddSingleton<IApplicationEnvironment, ApplicationEnvironment>();
            serviceCollection.AddSingleton<IApplicationLifetime, ApplicationLifetime>();

            serviceCollection.AddLogging();
            _configureServices?.Invoke(serviceCollection);

            _services = serviceCollection.BuildServiceProvider();
            var odysseyHost = new OdysseyConsoleHost(serviceCollection, _services);
            return odysseyHost;
        }

        public HostBuilder ConfigureServices(Action<IServiceCollection> configurationServices)
        {
            _configureServices += configurationServices;
            return this;
        }

        public HostBuilder UseStartup(Type startupType)
        {
            var startupAssemblyName = startupType.GetTypeInfo().Assembly.GetName().Name;
            var typeOfStartUp = typeof(IStartup);
            if (!typeOfStartUp.IsAssignableFrom(startupType))
            {
                throw new ArgumentException("Startup类型异常,请先继承 Odyssey.IStartup接口");
            }
            ConfigureServices((services) =>
            {
                services.AddSingleton(typeof(IStartup), startupType);
            });
            return this;
        }
    }
}
